<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Feign客户端演示</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body {
            padding: 20px;
            background-color: #f8f9fa;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
        }
        .server-box {
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            text-align: center;
        }
        .current-server {
            background-color: #e7f5ff;
            border: 2px solid #4dabf7;
        }
        .target-server {
            background-color: #fff9db;
            border: 2px solid #ffd43b;
        }
        .port-badge {
            font-size: 24px;
            padding: 5px 15px;
        }
        .port-8081 {
            background-color: #4dabf7;
        }
        .port-8082 {
            background-color: #ff922b;
        }
        .control-panel {
            margin: 30px 0;
            padding: 20px;
            background-color: #f1f3f5;
            border-radius: 8px;
        }
        .result-panel {
            margin-top: 30px;
            min-height: 300px;
        }
        .call-history {
            max-height: 300px;
            overflow-y: auto;
        }
        .history-item {
            padding: 10px;
            margin-bottom: 5px;
            border-radius: 5px;
        }
        #statistics {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center mb-4">Feign客户端演示</h1>
        
        <div class="row">
            <div class="col-md-6">
                <div class="server-box current-server">
                    <h3>当前服务实例</h3>
                    <span class="badge port-badge" id="currentPort">等待...</span>
                    <p class="mt-2">您正在访问的服务实例端口</p>
                </div>
            </div>
            <div class="col-md-6">
                <div class="server-box target-server">
                    <h3>目标服务实例</h3>
                    <span class="badge port-badge" id="targetPort">等待调用...</span>
                    <p class="mt-2">Feign调用的目标实例端口</p>
                </div>
            </div>
        </div>
        
        <div class="control-panel">
            <h3>控制面板</h3>
            <div class="row mb-3">
                <div class="col-md-6">
                    <button id="callOnceBtn" class="btn btn-primary w-100">单次调用</button>
                </div>
                <div class="col-md-6">
                    <button id="multipleCallsBtn" class="btn btn-success w-100">多次调用 (20次)</button>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <label for="userId">用户ID：</label>
                        <div class="input-group">
                            <input type="number" id="userId" class="form-control" value="1">
                            <button id="getLostItemsBtn" class="btn btn-info">获取失物信息</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="result-panel">
            <h3>调用历史</h3>
            <div id="callHistory" class="call-history">
                <div class="alert alert-info">点击"单次调用"或"多次调用"按钮开始测试</div>
            </div>
            
            <div id="statistics" style="display: none;">
                <h3>统计信息</h3>
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5>端口 8081</h5>
                                <div class="progress">
                                    <div id="port8081Progress" class="progress-bar bg-primary" role="progressbar" style="width: 0%">0%</div>
                                </div>
                                <p class="mt-2">调用次数: <span id="port8081Count">0</span></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5>端口 8082</h5>
                                <div class="progress">
                                    <div id="port8082Progress" class="progress-bar bg-warning" role="progressbar" style="width: 0%">0%</div>
                                </div>
                                <p class="mt-2">调用次数: <span id="port8082Count">0</span></p>
                            </div>
                        </div>
                    </div>
                </div>
                <p class="mt-3">总调用次数: <span id="totalCount">0</span></p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const callOnceBtn = document.getElementById('callOnceBtn');
            const multipleCallsBtn = document.getElementById('multipleCallsBtn');
            const getLostItemsBtn = document.getElementById('getLostItemsBtn');
            const userId = document.getElementById('userId');
            const currentPort = document.getElementById('currentPort');
            const targetPort = document.getElementById('targetPort');
            const callHistory = document.getElementById('callHistory');
            const statistics = document.getElementById('statistics');
            
            const port8081Count = document.getElementById('port8081Count');
            const port8082Count = document.getElementById('port8082Count');
            const port8081Progress = document.getElementById('port8081Progress');
            const port8082Progress = document.getElementById('port8082Progress');
            const totalCount = document.getElementById('totalCount');
            
            let counts = {
                '8081': 0,
                '8082': 0,
                'total': 0
            };
            
            // 获取当前端口
            fetch('/api/instance/info')
                .then(response => response.json())
                .then(data => {
                    currentPort.textContent = data.port;
                    currentPort.className = `badge port-badge port-${data.port}`;
                })
                .catch(error => {
                    console.error('Error:', error);
                    currentPort.textContent = 'Error';
                    currentPort.className = 'badge bg-danger';
                });
            
            // 单次调用
            callOnceBtn.addEventListener('click', function() {
                callService();
            });
            
            // 多次调用
            multipleCallsBtn.addEventListener('click', function() {
                const times = 20;
                multipleCallsBtn.disabled = true;
                multipleCallsBtn.textContent = '调用中...';
                
                fetch(`/api/feign/test-loadbalancer/${times}`)
                    .then(response => response.json())
                    .then(data => {
                        // 清空历史记录
                        callHistory.innerHTML = '';
                        
                        // 添加统计信息
                        const historyItem = document.createElement('div');
                        historyItem.className = 'history-item alert alert-success';
                        
                        let statsHtml = `<strong>调用统计：</strong><br>`;
                        let total = 0;
                        
                        for (const [port, count] of Object.entries(data.statistics)) {
                            total += count;
                            const percentage = (count / times * 100).toFixed(1);
                            statsHtml += `端口 ${port}: ${count} 次 (${percentage}%)<br>`;
                            
                            if (port === '8081') {
                                port8081Count.textContent = count;
                                port8081Progress.style.width = `${percentage}%`;
                                port8081Progress.textContent = `${percentage}%`;
                                counts['8081'] = count;
                            } else if (port === '8082') {
                                port8082Count.textContent = count;
                                port8082Progress.style.width = `${percentage}%`;
                                port8082Progress.textContent = `${percentage}%`;
                                counts['8082'] = count;
                            }
                        }
                        
                        counts.total = total;
                        totalCount.textContent = total;
                        
                        historyItem.innerHTML = statsHtml;
                        callHistory.appendChild(historyItem);
                        
                        statistics.style.display = 'block';
                        
                        multipleCallsBtn.disabled = false;
                        multipleCallsBtn.textContent = '多次调用 (20次)';
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        const historyItem = document.createElement('div');
                        historyItem.className = 'history-item alert alert-danger';
                        historyItem.textContent = `调用失败: ${error.message}`;
                        callHistory.appendChild(historyItem);
                        
                        multipleCallsBtn.disabled = false;
                        multipleCallsBtn.textContent = '多次调用 (20次)';
                    });
            });
            
            // 获取失物信息
            getLostItemsBtn.addEventListener('click', function() {
                const userIdValue = userId.value;
                if (!userIdValue) {
                    alert('请输入用户ID');
                    return;
                }
                
                getLostItemsBtn.disabled = true;
                getLostItemsBtn.textContent = '获取中...';
                
                fetch(`/api/feign/lost-items/${userIdValue}`)
                    .then(response => response.json())
                    .then(data => {
                        const historyItem = document.createElement('div');
                        historyItem.className = 'history-item alert alert-info';
                        
                        let itemsHtml = `<strong>用户 ${userIdValue} 的失物信息：</strong><br>`;
                        itemsHtml += `总数：${data.count}<br>`;
                        
                        if (data.count > 0) {
                            itemsHtml += '<ul>';
                            data.items.forEach(item => {
                                itemsHtml += `<li>${item.name || '未命名物品'}</li>`;
                            });
                            itemsHtml += '</ul>';
                        } else {
                            itemsHtml += '没有失物记录';
                        }
                        
                        historyItem.innerHTML = itemsHtml;
                        callHistory.insertBefore(historyItem, callHistory.firstChild);
                        
                        getLostItemsBtn.disabled = false;
                        getLostItemsBtn.textContent = '获取失物信息';
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        const historyItem = document.createElement('div');
                        historyItem.className = 'history-item alert alert-danger';
                        historyItem.textContent = `调用失败: ${error.message}`;
                        callHistory.insertBefore(historyItem, callHistory.firstChild);
                        
                        getLostItemsBtn.disabled = false;
                        getLostItemsBtn.textContent = '获取失物信息';
                    });
            });
            
            function callService() {
                callOnceBtn.disabled = true;
                callOnceBtn.textContent = '调用中...';
                
                fetch('/api/feign/instance-info')
                    .then(response => response.json())
                    .then(data => {
                        const targetPortValue = data.port;
                        targetPort.textContent = targetPortValue;
                        targetPort.className = `badge port-badge port-${targetPortValue}`;
                        
                        // 更新历史记录
                        const historyItem = document.createElement('div');
                        historyItem.className = 'history-item bg-light';
                        const timestamp = new Date().toLocaleTimeString();
                        historyItem.innerHTML = `
                            <strong>${timestamp}</strong>: 
                            从端口 <span class="badge bg-primary">${data.sourcePort}</span> 
                            调用到端口 <span class="badge bg-${targetPortValue === '8081' ? 'primary' : 'warning'}">${targetPortValue}</span>
                            <br>
                            <small>使用 ${data.clientType} 客户端</small>
                        `;
                        callHistory.insertBefore(historyItem, callHistory.firstChild);
                        
                        // 更新统计信息
                        counts[targetPortValue] = (counts[targetPortValue] || 0) + 1;
                        counts.total += 1;
                        
                        port8081Count.textContent = counts['8081'];
                        port8082Count.textContent = counts['8082'];
                        totalCount.textContent = counts.total;
                        
                        // 更新进度条
                        const port8081Percentage = (counts['8081'] / counts.total * 100).toFixed(1);
                        const port8082Percentage = (counts['8082'] / counts.total * 100).toFixed(1);
                        
                        port8081Progress.style.width = `${port8081Percentage}%`;
                        port8081Progress.textContent = `${port8081Percentage}%`;
                        
                        port8082Progress.style.width = `${port8082Percentage}%`;
                        port8082Progress.textContent = `${port8082Percentage}%`;
                        
                        statistics.style.display = 'block';
                        
                        callOnceBtn.disabled = false;
                        callOnceBtn.textContent = '单次调用';
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        const historyItem = document.createElement('div');
                        historyItem.className = 'history-item alert alert-danger';
                        historyItem.textContent = `调用失败: ${error.message}`;
                        callHistory.insertBefore(historyItem, callHistory.firstChild);
                        
                        callOnceBtn.disabled = false;
                        callOnceBtn.textContent = '单次调用';
                    });
            }
        });
    </script>
</body>
</html> 